﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_CirculationBillItemBusiness : BaseBusiness<PB_CirculationBillItem>, IPB_CirculationBillItemBusiness, ITransientDependency
    {
        public PB_CirculationBillItemBusiness(IDbAccessor db)
            : base(db)
        {
        }

        #region 外部接口

        public async Task<PageResult<PB_CirculationBillItem>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_CirculationBillItem>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_CirculationBillItem, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_CirculationBillItem> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_CirculationBillItem data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_CirculationBillItem data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }
        /// <summary>
        /// 半成品耗用流水
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_CirculationBillItemDTO>> GetDataDTOListAsync(PageInput<PB_CirculationBillItemConditionDTO> input) 
        {
            Expression<Func<PB_CirculationBillItem, PB_ProductionOrder, PB_Tray, PB_Material, Base_User, PB_Material, PB_CirculationBillItemDTO>> select = (a, b, c, d, e, f) => new PB_CirculationBillItemDTO
            {
                TaskCode = b.Id,
                TaskName = b.POName,
                ProductName = d.Name,
                Tray = c.Code,
                Creator = e.RealName,
                SubordinateProductName = f.Name
            };
            var search = input.Search;
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_ProductionOrder>() on a.OrderId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Tray>() on a.TrayId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Material>() on a.MaterialId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    join e in Db.GetIQueryable<Base_User>() on a.CollectionUserId equals e.Id into ae
                    from e in ae.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_Material>() on a.SubordinateProduct equals f.Id into af
                    from f in af.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d, e,f);
            if (!input.Search.TaskCode.IsNullOrEmpty())
            {
                q = q.Where(x => x.TaskCode.Contains(input.Search.TaskCode));
            }
            if (!input.Search.TaskName.IsNullOrEmpty())
            {
                q = q.Where(x => x.TaskName.Contains(input.Search.TaskName) );
            }
            if (!input.Search.StartDate.IsNullOrEmpty() && !input.Search.EndDate.IsNullOrEmpty())
            {
                DateTime StartDate = Convert.ToDateTime(Convert.ToDateTime(input.Search.StartDate).Date.ToString());
                DateTime EndDate = Convert.ToDateTime(Convert.ToDateTime(input.Search.EndDate).Date.ToString()).AddDays(1).AddSeconds(-1);

                q = q.Where(x => StartDate <= x.CollectionTime && x.CollectionTime <= EndDate);

            }
            if (!input.Search.ProductName.IsNullOrEmpty())
            {
                q = q.Where(x => x.ProductName.Contains(input.Search.ProductName));
            }

            if (!input.Search.SubordinateProductName.IsNullOrEmpty())
            {
                q = q.Where(x => x.SubordinateProductName.Contains(input.Search.SubordinateProductName));
            }
            if (!input.Search.Tray.IsNullOrEmpty())
            {
                q = q.Where(m => m.Tray == input.Search.Tray);
            }
            if (!input.Search.Creator.IsNullOrEmpty())
            {
                q = q.Where(m => m.Creator == input.Search.Creator);
            }
          //  q = q.OrderByDescending(s => s.CollectionTime);
            return await q.GetPageResultAsync(input);
        }
        public async Task<PageResult<PB_CirculationBillItemDTO>> GetDataByDayDTOListAsync(PageInput<PB_CirculationBillItemConditionDTO> input)
        {
            string str = @"select b.id as TaskCode ,b.POName as TaskName,d.name as ProductName,e.Id as ProcedureId,e.`Name` as ProcedureName,f.name as SubordinateProductName, DATE_FORMAT(a.CollectionTime,'%Y-%m-%d') as CreateDay,sum(a.nums) as nums from PB_CirculationBillItem a left join PB_ProductionOrder b on a.OrderId=b.Id
              left join PB_Material d on a.MaterialId=d.Id
                left join PB_Material f on a.SubordinateProduct=f.Id
								left join PB_CirculationBill as c on a.CirBillId=c.Id
								left join PB_ProcecureSub as e on c.ProcedureId=e.Id where 1=1 ";
            if (!input.Search.TaskCode.IsNullOrEmpty())
            {
                str += " and b.id like '%"+ input.Search.TaskCode + "%' ";
            }
            if (!input.Search.TaskName.IsNullOrEmpty())
            {
                str += " and b.POName like '%" + input.Search.TaskName + "%' ";
            }
            if (!input.Search.ProductName.IsNullOrEmpty())
            {
                str += " and d.name like '%" + input.Search.ProductName + "%' ";
            }
            if (!input.Search.SubordinateProductName.IsNullOrEmpty())
            {
                str += " and f.name like '%" + input.Search.SubordinateProductName + "%' ";
            }
            if (!input.Search.ProcedureId.IsNullOrEmpty())
            {
                str += " and e.Id='" + input.Search.ProcedureId + "' ";
            }
            if (!input.Search.StartDate.IsNullOrEmpty() && !input.Search.EndDate.IsNullOrEmpty())
            {
                str += " and DATE_FORMAT(a.CollectionTime,'%Y-%m-%d') between '" + input.Search.StartDate + "' and '" + input.Search.EndDate + "' ";
            }
            str += " GROUP BY b.id  ,b.POName ,d.name,e.Id,e.`Name`,f.name , DATE_FORMAT(a.CollectionTime,'%Y-%m-%d') ";
            str += "order  by "+input.SortField+" "+input.SortType+" ";
            var lidata = await Db.GetListBySqlAsync<PB_CirculationBillItemDTO>(str);
            int num = lidata.Count;
            var list = lidata
               .Skip((input.PageIndex - 1) * input.PageRows)
               .Take(input.PageRows).ToList();
            return new PageResult<PB_CirculationBillItemDTO> { Data = list, Total = num };
        }
        /// <summary>
        /// 托盘流水
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<TrayFlowDTO>> GetTrayFlowDTOListAsync(PageInput<TrayFlowConditionDTO> input)
        {
            string str = @"SELECT * from (
                    SELECT a.SendTime CreateTime,c.POName,a.DispatchId,e.`Name` ProcessingName,CONCAT(d.PunchingPosition,d.Texture,d.Aperture) ProcessingRequirements,f.Id as ProcedureId,f.`Name` as ProcedureName,'报工' Type,b.`Code` TrayName,a.WorkReportQuantity Nums,g.RealName Creator  from PB_CirculationBill a 
                    left join PB_Tray b on a.TrayId=b.id 
                    left join PB_ProductionOrder c on a.TaskId=c.id 
                    left join PB_DispatchDetail d on a.DispatchDetailId=d.id 
                    left join PB_Material e on d.MaterialId=e.id 
                    left join PB_ProcecureSub f on a.ProcedureId=f.id   
                    left join Base_User g on a.CreatorId=g.id 
                     union all
                    SELECT a.CollectionTime CreateTime,b.POName,a.DispatchId,e.`Name` ProcessingName,CONCAT(d.PunchingPosition,d.Texture,d.Aperture) ProcessingRequirements,'' ProcedureId,'' ProcedureName,'领用' Type,c.`Code` TrayName,a.Nums,g.RealName Creator from PB_CirculationBillItem a 
                    left join PB_ProductionOrder b on a.OrderId=b.id
                    left join PB_Tray c on a.TrayId=c.id  
                    left join PB_DispatchDetail d on a.DispatchDetailId=d.id 
                    left join PB_Material e on d.MaterialId=e.id 
                    left join Base_User g on a.CreatorId=g.id ) a where 1=1 ";
            if (!input.Search.POName.IsNullOrEmpty())
            {
                str += " and POName like '%" + input.Search.POName + "%' ";
            }
            if (!input.Search.DispatchId.IsNullOrEmpty())
            {
                str += " and DispatchId like '%" + input.Search.DispatchId + "%' ";
            }
            if (!input.Search.ProcessingName.IsNullOrEmpty())
            {
                str += " and ProcessingNamelike '%" + input.Search.ProcessingName + "%' ";
            }
            if (!input.Search.ProcessingRequirements.IsNullOrEmpty())
            {
                str += " and ProcessingRequirements like '%" + input.Search.ProcessingRequirements + "%' ";
            }
            if (!input.Search.ProcedureName.IsNullOrEmpty())
            {
                str += " and ProcedureId='" + input.Search.ProcedureName + "' ";
            }
            if (!input.Search.Type.IsNullOrEmpty())
            {
                str += " and Type like '%" + input.Search.Type + "%' ";
            }
            if (!input.Search.TrayName.IsNullOrEmpty())
            {
                str += " and TrayName like '%" + input.Search.TrayName + "%' ";
            }
            if (!input.Search.Creator.IsNullOrEmpty())
            {
                str += " and Creator like '%" + input.Search.Creator + "%' ";
            }
            if (!input.Search.StartDate.IsNullOrEmpty() && !input.Search.EndDate.IsNullOrEmpty())
            {
                str += " and DATE_FORMAT(CreateTime,'%Y-%m-%d') between '" + input.Search.StartDate + "' and '" + input.Search.EndDate + "' ";
            }
            str += " ORDER BY "+input.SortField+" "+input.SortType+"  ";
            var lidata = await Db.GetListBySqlAsync<TrayFlowDTO>(str);
            int num = lidata.Count;
            var list = lidata
               .Skip((input.PageIndex - 1) * input.PageRows)
               .Take(input.PageRows).ToList();
            return new PageResult<TrayFlowDTO> { Data = list, Total = num };
        }
        #endregion

        #region 私有成员

        #endregion
    }
}